﻿using Mt.Site.Core.WorkFlows.Design.Cache;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Mt.Site.Core.WorkFlows.Design
{
    internal class DefaultWorkflowDefinition : IWorkflowDefinition
    {
        public IWorkFlowCacheItem Definition { get; set; }

        public IWorkflowNodeDefinition FirstNode
        {
            get
            {
                var cacheNodeItem = Definition.NodeList.FirstOrDefault(c=>c.IsActive);
                return CreateNodeDef(cacheNodeItem);
            }
        }

        public IWorkflowNodeDefinition FindNode(Guid nodeId)
        {
            var cacheNodeItem = Definition.NodeList.FirstOrDefault(c=>c.NodeId == nodeId);
            return CreateNodeDef(cacheNodeItem);
        }

        public IWorkflowNodeDefinition FindNode(string nodeName)
        {
            var cacheNodeItem = Definition.NodeList.FirstOrDefault(c => c.Name == nodeName);
            return CreateNodeDef(cacheNodeItem);
        }


        public List<IWorkflowNodeDefinition> GetNodeList(List<Guid> idList)
        {
            return idList.Select(id => Definition.NodeList.FirstOrDefault(d => d.NodeId == id))
                .Select(c => CreateNodeDef(c))
                .Where(c => c != null)
                .ToList();
        }

        private IWorkflowNodeDefinition CreateNodeDef(IWorkFlowNodeCacheItem cacheNodeItem)
        {
            if (cacheNodeItem != null)
            {
                return new DefaultWorkflowNodeDefinition
                {
                    Definition = cacheNodeItem,
                    WorkFlow = this
                };
            }
            return null;
        }
    }
}
